<?php
/**
 * @ClassName: Customer
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-11-13 16:20
 * @Version: V1.0.0
 */

namespace app\admin\controller\customer;

use app\common\enum\CustomerEnum;
use app\common\model;
use think\Controller;
use tpext\areacity\api\model\Areacity;
use tpext\builder\traits\HasBuilder;

class Customer extends Controller
{
    use HasBuilder;

    protected $dataModel;

    protected function initialize()
    {
        parent::initialize();

        $this->dataModel = new model\Customer();
        $this->pageTitle = '客户管理';
        $this->pagesize = 10;

        $this->indexWith = [];

        $this->selectTextField = '{id}#{customer_name}';
        $this->selectSearch = 'id|customer_name|business_license|credit_code';
    }

    /**
     * 构建搜索
     *
     * @return void
     */
    protected function buildSearch()
    {
        $search = $this->search;

        $search->text('keyword', '关键字');
        $search->select('customer_type', '客户类型')->options(CustomerEnum::customerTypeText(true));
        $search->select('star_level', '客户星级')->dataUrl(url('/admin/customer.customerstarlevel/selectPage'));
        $search->select('month_settle', '月结状态')->options(CustomerEnum::monthSettleStatus(true));

        $search->select('province', '省份')->dataUrl(url('api/areacity/province'), 'ext_name')->withNext(
            $search->select('city', '城市')->dataUrl(url('api/areacity/city'), 'ext_name')->withNext(
                $search->select('area', '地区')->dataUrl(url('api/areacity/area'), 'ext_name')
            )
        );
        $search->text('address', '客户地址');
    }

    /**
     * 构建搜索条件
     * @return array
     */
    protected function filterWhere()
    {
        $searchData = request()->get();

        $where = [];
        if (isset($searchData['keyword']) && $searchData['keyword'] != '') {
            $where[] = ['customer_name|business_license|credit_code', 'like', '%' . trim($searchData['keyword']) . '%'];
        }
        if (isset($searchData['customer_type']) && $searchData['customer_type'] != '') {
            $where[] = ['customer_type', 'eq', $searchData['customer_type']];
        }
        if (isset($searchData['star_level']) && $searchData['star_level'] != '') {
            $where[] = ['star_level', 'eq', $searchData['star_level']];
        }
        if (isset($searchData['month_settle']) && $searchData['month_settle'] != '') {
            $where[] = ['month_settle', 'eq', $searchData['month_settle']];
        }
        if (isset($searchData['address']) && $searchData['address'] != '') {
            $where[] = ['address', 'like', '%' . $searchData['address'] . '%'];
        }
        if (isset($searchData['province']) && $searchData['province'] != '') {
            $where[] = ['province', 'eq', $searchData['province']];

            if (isset($searchData['city']) && $searchData['city'] != '') {
                $where[] = ['city', 'eq', $searchData['city']];

                if (isset($searchData['area']) && $searchData['area'] != '') {
                    $where[] = ['area', 'eq', $searchData['area']];
                }
            }
        }

        return $where;
    }

    /**
     * 构建表格
     *
     * @return void
     */
    protected function buildTable(&$data = [])
    {
        $table = $this->table;

        $starLevelList = model\CustomerStarLevel::select();

        $table->show('id', 'ID');
        $table->match('customer_type', '客户类型')->options(CustomerEnum::customerTypeText(true));
        $table->show('customer_name', '客户名称');
        $table->image('avatar', '头像')->thumbSize(50, 50)->default('/static/images/touxiang.png');
        $table->show('fullname', '联系人');
        $table->show('mobile', '联系电话');
        $table->match('water_users', '喝水人数')->to('{val}人');
        $table->match("star_level", "客户星级")->optionsData($starLevelList, "name", "id");
        $table->match('month_settle', '月结状态')->options(CustomerEnum::monthSettleStatus(true));
        $table->show('pcat', '省市区')->default('---');
        $table->show('address', '客户地址')->default('---');

        $table->fields('times_group', '添加/修改时间')->with(
            $table->show('create_time', '添加时间')->default('---'),
            $table->show('update_time', '修改时间')->default('---')
        )->getWrapper()->addStyle('width:160px');

        $table->sortable('id, create_time');

        $table->getToolbar()
            ->btnAdd()
            ->btnRefresh();

        $table->getActionbar()
            ->btnEdit()
            ->btnView()
            ->btnLink('bindWaterRack', url('bindWaterRack', ['id' => '__data.pk__']), '绑定水架', 'btn-info', 'mdi mdi-coin', 'data-layer-size="50%,50%"')
            ->btnLink('bindMaster', url('/admin/customermaster/index', ['customer_id' => '__data.pk__']), '送水师傅', 'btn-info', 'mdi mdi-coin', 'data-layer-size="80%,80%"');
    }

    /**
     * 构建表单
     *
     * @param boolean $isEdit
     * @param array $data
     */
    protected function buildForm($isEdit, &$data = [])
    {
        $form = $this->form;

        $form->hidden('id');

        if ($isEdit) {
            $data['contacts'] = model\CustomerContacts::where('customer_id', $data['id'])->find();
            $data['invoice'] = model\Invoice::where('customer_id', $data['id'])->find();

            if ($data['contacts']) {
                $data['contacts_id'] = $data['contacts']['id'];
            } else {
                $data['contacts_id'] = 0;
            }

            if ($data['invoice']) {
                $data['invoice_id'] = $data['invoice']['id'];
            } else {
                $data['invoice_id'] = 0;
            }
        }

        $tab = input('tab', 0);
        $form->tab('基本信息')->with(
            function () use ($data, $isEdit, $form) {
                $form->select('customer_type', '客户类型')->options(CustomerEnum::customerTypeText(true))->when([2, 3])->with(
                    $form->text('business_license', '营业执照名称')->required(),
                    $form->text('credit_code', '企业信用代码')->required()
                )->required();
                $form->text('customer_name', '客户名称')->required();
                $form->image('avatar', '头像')->thumbSize(50, 50)->default('/static/images/touxiang.png');
                $form->select('water_users', '喝水人数')->options(CustomerEnum::waterUsers(true))->required();
                $form->select('star_level', '客户星级')->dataUrl(url('/admin/customer.customerstarlevel/selectPage'))->required();

                if ($isEdit) {
                    // 编辑
                    $form->radio('spread_type', '推广类型')->options(CustomerEnum::spreadTypes(true))->default(-1)->required()
                        ->when(1)->with(
                        // 师傅
                            $form->select('promoter', '推广人')->dataUrl(url('/admin/member/selectMemberPage?type=4'))->required(),
                        )
                        ->when(2)->with(
                        // 代理
                            $form->select('promoter', '推广人')->dataUrl(url('/admin/member/selectMemberPage?type=3'))->required(),
                        )
                        ->when(3)->with(
                        // 商家
                            $form->select('promoter', '推广人')->dataUrl(url('/admin/member/selectMemberPage?type=1'))->required(),
                        );
                } else {
                    // 新增
                    $form->radio('spread_type', '推广类型')->options(CustomerEnum::spreadTypes(true))->default(-1)->required()
                        ->when(1)->with(
                        // 师傅
                            $form->select('promoter', '推广人')->dataUrl(url('/admin/member/selectMemberPage?type=4'))->required(),
                            $form->hidden('master_id')
                        )
                        ->when(2)->with(
                        // 代理
                            $form->select('promoter', '推广人')->dataUrl(url('/admin/member/selectMemberPage?type=3'))->required(),
                            $form->select('master_id', '送水师傅')->dataUrl(url('/admin/member/selectMemberPage?type=4'))->required()
                        )
                        ->when(3)->with(
                        // 商家
                            $form->select('promoter', '推广人')->dataUrl(url('/admin/member/selectMemberPage?type=1'))->required(),
                            $form->select('master_id', '送水师傅')->dataUrl(url('/admin/member/selectMemberPage?type=4'))->required()
                        );
                }

                $form->radio('is_ad_put', '是否适合投放广告')->options([0 => '不能', 1 => '能'])->default(0)->required();
                $form->radio('has_elevator', '是否有电梯')->options([0 => '无', 1 => '有'])->default(1)->required()->when(0)->with(
                    $form->number('floor', '楼层')->default(1)->required()
                );
                $form->text('service_date', '定期送水')->help('可设置每月几号定期送水');
                $form->text('tags', '标签')->help('多个标签使用逗号‘,’分割。');
                $form->radio('month_settle', '月结状态')->options(CustomerEnum::monthSettleStatus(true))->default(0)
                    ->when(1)->with(
                        $form->text('settle_limit', '月结额度')->required(),
                        $form->show('use_limit', '使用额度'),
                        $form->text('settle_date', '月结算日期')->default(25)->required()->help('每月什么时候结算就填写几号')
                    )->required();
                $form->textarea('remark', '备注');

                if ($isEdit) {
                    $form->show('create_time', '添加时间');
                    $form->show('update_time', '更新时间');
                }
            }
        );

        $form->tab('主要联系人')->with(
            $form->hidden('contacts_id'),
            $form->select('contacts.member_id', '会员')->dataUrl(url('/admin/member/selectPage')),
            $form->text('contacts.name', '姓名')->required(),
            $form->text('contacts.subname', '简称或尊称'),
            $form->text('contacts.mobile', '手机号')->required(),
            $form->switchBtn('contacts.is_major', '是否主要联系人')->default(1)->readonly(),
            $form->text('contacts.role', '角色'),
            $form->text('contacts.post', '职务'),
            $form->text('contacts.email', '邮箱')
        );

        $form->tab('发票信息')->with(
            function () use ($data, $isEdit, $form) {
                $form->hidden('invoice_id');
                $form->radio('need_invoice', '发票')->options([0 => '无', 1 => '普票', 2 => '专票'])->default(0)->required()
                    ->when(1)->with(
                        $form->hidden('invoice.type')->default(1),
                        $form->radio('invoice.header_type', '抬头类型')->options([1 => '个人', 2 => '企业'])->default(1)->required(),
                        $form->text('invoice.name', '发票抬头')->required(),
                        $form->text('invoice.duty_number', '税号')->required(),
                        $form->text('invoice.drawer_phone', '开票人手机号'),
                        $form->text('invoice.email', '开票人邮箱'),
                        $form->switchBtn('invoice.is_default', '默认')->default(1)->required()
                    )->when(2)->with(
                        $form->hidden('invoice.header_type')->default(2),
                        $form->hidden('invoice.type')->default(2),
                        $form->text('invoice.name', '发票抬头')->required(),
                        $form->text('invoice.duty_number', '税号')->required(),
                        $form->text('invoice.bank', '注册开户银行')->required(),
                        $form->text('invoice.card_number', '银行卡号')->required(),
                        $form->text('invoice.tell', '注册电话')->required(),
                        $form->text('invoice.address', '注册地址')->required(),
                        $form->text('invoice.drawer_phone', '开票人手机号'),
                        $form->text('invoice.email', '开票人邮箱'),
                        $form->switchBtn('invoice.is_default', '默认')->default(1)->required()
                    );
            }
        );

        $selectP = Areacity::where(['id' => $store['province'] ?? 0])->field('id,ext_name')->select();
        $selectC = Areacity::where(['id' => $store['city'] ?? 0])->field('id,ext_name')->select();
        $selectA = Areacity::where(['id' => $store['area'] ?? 0])->field('id,ext_name')->select();
        $selectT = Areacity::where(['id' => $store['town'] ?? 0])->field('id,ext_name')->select();
        $form->tab('位置信息')->with(
            $form->fields('省/市/区/街道')->fullSize(2)->required(),
            $form->select('province', '省份', 3)->size(0, 12)->showLabel(false)->optionsData($selectP, 'ext_name')->dataUrl(url('api/areacity/province'), 'ext_name')->withNext(
                $form->select('city', '城市', 3)->size(0, 12)->showLabel(false)->optionsData($selectC, 'ext_name')->dataUrl(url('api/areacity/city'), 'ext_name')->withNext(
                    $form->select('area', '区县', 3)->size(0, 12)->showLabel(false)->optionsData($selectA, 'ext_name')->dataUrl(url('api/areacity/area'), 'ext_name')->withNext(
                        $form->select('town', '乡镇', 3)->size(0, 12)->showLabel(false)->optionsData($selectT, 'ext_name')->dataUrl(url('api/areacity/town'), 'ext_name')
                    )
                )
            ),
            $form->fieldsEnd(),

            $form->textarea('address', '详细地址')->required(),
            $form->map('location', '位置')->required()
        );
    }

    /**
     * 绑定水架
     * @return \think\response\Json|\tpext\builder\common\Builder|\tpext\think\View
     */
    public function bindWaterRack()
    {
        $builder = $this->builder('绑定水架');

        $id = input('id/d', '');

        if (empty($id)) {
            $this->error('参数有误');
        }

        $customer = model\Customer::where('id', $id)->find();
        if (!$customer) {
            return json(['code' => 0, 'msg' => '客户信息不存在']);
        }

        // 1.展示页面
        if (request()->isGet()) {
            $form = $builder->form();
            $form->fill($customer);
            $form->match('id', '客户')->to('{val}#{customer_name}');
            $form->select('rack_id', '水架')->dataUrl(url('selectRackPage?status=0'))->required();
            return $builder;
        } else {
            $rack_id = input('rack_id');
            /*var_dump('客户ID：' . $id);
            var_dump('水架ID：' . $rack_id);*/

            $rack = model\WaterRack::where('id', $rack_id)->where('status', 0)->find();
            if (!$rack) {
                return json(['code' => 0, 'msg' => '架子不存在或已经在使用中']);
            }
            $contacts = model\CustomerContacts::where('customer_id', $id)->find();

            $data = [
                'customer_id' => $id,
                'rack_id' => $rack_id,
                'status' => 1,
                'inventory' => 0,
                'grids_num' => $rack['grids_num'],
                'bucketful_num' => 0,
                'empty_bucket_num' => $rack['grids_num'],
                'province' => $customer['province'],
                'city' => $customer['city'],
                'area' => $customer['area'],
                'town' => $customer['town'],
                'address' => $customer['address'],
                'longitude' => $customer['longitude'],
                'latitude' => $customer['latitude'],
            ];

            $res = model\EquipmentCustomer::insert($data);
            if ($res) {
                $res1 = model\WaterRack::where('id', $id)->update([
                    'status' => 1,
                    'update_time' => date('Y-m-d H:i:s'),
                ]);
                if (!$res1) {
                    return $builder->layer()->closeRefresh(true, "提交失败");
                }
            } else {
                return $builder->layer()->closeRefresh(true, "提交失败");
            }

            return $builder->layer()->closeRefresh(true, "提交成功");
        }
    }

    /**
     * 保存数据
     *
     * @param integer $id
     * @return void
     */
    private function save($id = 0)
    {
        $data = request()->post();

        $result = $this->validate($data, []);

        if (!$result) {
            $this->error($result);
        }

        if ($id) {
            // 编辑
            $data['update_time'] = date_now();
        } else {
            // 新增
            $data['create_time'] = date_now();
            $data['update_time'] = date_now();
        }

        return $this->doSave($data, $id);
    }
}